package com.bwie.common.handler;

import com.bwie.common.exception.BizException;
import com.bwie.common.result.Result;
import com.bwie.common.utils.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {
    @ExceptionHandler(BizException.class)
    public Result bizExceptionHandler(HttpServletRequest request,BizException e){
        log.info("请求的url：{}发生异常，异常信息为：{}",request.getRequestURI(),e.getMsg());
        return Result.error(e.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(HttpServletRequest request,MethodArgumentNotValidException e){
        log.info("请求的uel：{}发生校验错误，错误的信息为：{}",request.getRequestURI(),e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        ArrayList<String> errorList = new ArrayList<>();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorList.add(fieldError.getDefaultMessage());
        }

        return Result.error(StringUtils.join(errorList,","));
    }

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e){
        e.printStackTrace();
        return Result.error("系统故障，请联系管理员");
    }
}
